﻿<template>
  <a-card :bordered="false">
    <div class="table-operator">
     <a-button type="primary" icon="plus" @click="hanldleAdd()" v-if="hasPerm('employeesign.Add')">新建</a-button>
      <!--  <a-button
      v-if="hasPerm('employeesign.Delete')"
        type="primary"
        icon="minus"
        @click="handleDelete(selectedRowKeys)"
        :disabled="!hasSelected()"
        :loading="loading"
      >删除</a-button> -->
      <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>
      
    </div>

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item label="查询类别">
              <a-select allowClear v-model="queryParam.condition">
                <!-- <a-select-option key="ServiceID">服务商ID</a-select-option> -->
                <a-select-option key="ServiceName">服务商名称</a-select-option>
                <a-select-option key="SignNo">签约编号</a-select-option>
                <a-select-option key="BeginDate">开始日期</a-select-option>
                <a-select-option key="SignVideoFile">签约视频文件地址</a-select-option>
              </a-select> 
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam.keyword" placeholder="关键字" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-button type="primary" @click="() => {this.pagination.current = 1; this.getDataList()}">查询</a-button>
            <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      :columns="columns"
      :rowKey="row => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="false"
      size="middle"
    >
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record.Id)" v-if="hasPerm('employeesign.Edit')">验签</a>
          <a-divider type="vertical" v-if="record.zt ==0"/>
          <a @click="UploadFile(record)" v-if="record.zt ==0">上传协议</a>
          <a-divider type="vertical" v-if="record.zt ==1"/>
          <a @click="downfile(record)" v-if="record.zt ==1">下载协议</a>
        </template>
      </span>
      <span slot="CreateTime" slot-scope="text, record">
        <span>
          起：{{record.BeginDate}}<br/>
          止：{{record.EndDate}}
        </span>
      </span>
      <span slot="zt" slot-scope="text">
        <span v-if="text == '1'"><a-tag color="green">已签约</a-tag></span>
        <span v-else-if="text == '0'"><a-tag color="blue">待签约</a-tag></span>
      </span>
    </a-table>

    <edit-form ref="editForm" :parentObj="this"></edit-form>


    <a-modal title="上传协议" width="70%" :visible="Signvisible" @ok="submitContrat" :confirmLoading="loading" @cancel="SignviewCancel">
    <a-upload
            list-type="picture"
            :customRequest="selfUpload1"
            :default-file-list="abc"
            :multiple="false"
            :before-upload="beforeUpload"
          >
            <a-button> <a-icon type="upload" /> 选择协议 </a-button>
            <div><span>上传文件大小不超过5MB,文件格式为.xls,.xlsx,.pdf</span></div>
          </a-upload>
    </a-modal>
  </a-card>
</template>

<script>
import EditForm from './EditForm'
import TokenCache from '@/utils/cache/TokenCache'
import OperatorCache from '@/utils/cache/OperatorCache'
const columns = [
  { title: '姓名', dataIndex: 'EmpName', width: '10%' },
  { title: '身份证号码', dataIndex: 'IdCardNo', width: '15%' },
  { title: '手机号码', dataIndex: 'EmpPhone', width: '15%' },
  { title: '企业名称', dataIndex: 'customerName', width: '15%' },
  { title: '起止日期', dataIndex: 'CreateTime', width: '20%',scopedSlots:{ customRender:'CreateTime' } },
  { title: '状态', dataIndex: 'zt', width: '10%',scopedSlots:{ customRender:'zt' } },
  { title: '操作', dataIndex: 'action', width:'15%', scopedSlots: { customRender: 'action' } },
];

export default {
  components: {
    EditForm
  },
  mounted() {
    this.getDataList()
  },
  data() {
    return {
      
      headers: { Authorization: 'Bearer ' + TokenCache.getToken() },
      Signvisible:false,
      data: [],
      abc:[],
      pagination: {
        current: 1,
        pageSize: 10,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`
      },
      signfileid:"",
      filters: {},
      sorter: { field: 'Id', order: 'asc' },
      loading: false,
      columns,
      queryParam: {},
      selectedRowKeys: []
    }
  },
  methods: {
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
      this.getDataList()
    },
    getDataList() {
      this.selectedRowKeys = []

      this.loading = true
      this.$http
        .post('/Base_leasesystem_employeesign/leasesystem_employeesign/GetDataListOver', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters
        })
        .then(resJson => {
          console.log(resJson.Data)
          this.loading = false
          this.data = resJson.Data.Data
          const pagination = { ...this.pagination }
          pagination.total = resJson.Data.Total
          this.pagination = pagination
        })
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    hanldleAdd() {
      this.queryParam.Keyword = "18817154130"
      console.log(this.queryParam)
      this.$http.post('/ThreeService/sendsms',{Search:this.queryParam}).then(res=>{
        console.log(res)
      })
    },
    handleEdit(id) {
      this.$refs.editForm.openForm(id)
    },
    handleDelete(ids) {
      var thisObj = this
          return new Promise((resolve, reject) => {
            thisObj.$http.post('/Base_leasesystem_employee/leasesystem_employee/DeleteData', ids).then(resJson => {
              resolve()

              if (resJson.Success) {
                thisObj.$message.success('操作成功!')

                thisObj.getDataList()
              } else {
                thisObj.$message.error(resJson.Msg)
              }
            })
          })
        
    },
    cancel(e) {
      this.$message.error('已取消删除');
    },
    UploadFile(row){
      console.log(row)
      this.signfileid = row.SignFiled
      this.abc = []
      this.Signvisible = true
    },
    SignviewCancel(){
      this.Signvisible = false
    },
    selfUpload1({ action, file, onSuccess, onError, onProgress }) {
      this.loading = true
      const formData = new FormData()
      let that = this
      formData.append('file', file)
      this.$http.post('/Base_Manage/Upload/UploadFileByForm', formData).then((res) => {
        this.abc.push(res)
        onSuccess(res,file)
        this.loading = false
      })
    },
    beforeUpload(file) {
      let fileType = file.name.split('.')
      const fileDate = fileType.slice(-1)
      if (['xlsx', 'xls', 'pdf'].indexOf(fileDate[0]) < 0) {
        this.$message.error('仅支持pdf,xls,xlsx 格式')
        return
      }
    },
    submitContrat() {
        let temp = {}
        temp.Rid = this.signfileid
        temp.FileName = this.abc[0].name
        temp.FilePathUrl = this.abc[0].uid
        temp.UpUserName = OperatorCache.info['UserName']
        temp.UpUserId = OperatorCache.info['Id']
        temp.ContractdownUrl = this.abc[0].url
        console.log(temp)
        this.$http.post('/Base_leasesystem_signfile/leasesystem_signfile/SaveDataEmpSign', temp).then((res) => {
          if (res.Success) {
            this.$message.success('操作成功')
            this.Signvisible = false;
            this.getDataList()
          } else {
            this.$message.error('操作失败')
          }
        })
      
    },
    downfile(row){
      this.queryParam.condition = "Rid"
      this.queryParam.keyword = row.SignFiled
      this.$http.post("/Base_leasesystem_signfile/leasesystem_signfile/GetDataList",{Search: this.queryParam})
      .then(res=>{
        console.log(res)
      let index = res.Data[0].ContractdownUrl.lastIndexOf("Upload")
      let spl = res.Data[0].ContractdownUrl.substr(index)

      var hou = res.Data[0].ContractdownUrl.split('.')
          this.$http.post('/Base_Manage/Upload/downSign',{id:spl},{responseType: 'blob'}).then(res =>{
            console.log(res)
          const blob = new Blob([res]);
          const fileName = "签约协议."+hou[hou.length-1];
          const elink = document.createElement('a');// 创建a标签
          elink.download = fileName;// 为a标签添加download属性
          // a.download = fileName; //命名下载名称
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();// 点击下载
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);// 释放标签
      })
      })

      
    },
  }
}
</script>

<style>
.ant-table-thead > tr > th
{
  font-weight: 600;
  color: #333333;
}
</style>